// Use Electron IPC for HTTP client or axios for development
import axios from 'axios'

let httpClient

if (window.require) {
  // Electron environment
  const { ipcRenderer } = window.require('electron')
  httpClient = {
    request: async (config) => {
      return await ipcRenderer.invoke('module:http-client:request', config)
    }
  }
} else {
  // Browser development environment - use axios directly
  httpClient = {
    request: async (config) => {
      try {
        const response = await axios(config)
        return {
          status: response.status,
          statusText: response.statusText,
          headers: response.headers,
          data: response.data,
          config: response.config
        }
      } catch (error) {
        if (error.response) {
          return {
            error: true,
            message: error.message,
            status: error.response.status,
            statusText: error.response.statusText,
            headers: error.response.headers,
            data: error.response.data
          }
        }
        return {
          error: true,
          message: error.message,
          code: error.code
        }
      }
    }
  }
}

const state = {
  requests: [],
  currentRequest: {
    method: 'GET',
    url: 'https://jsonplaceholder.typicode.com/posts/1',
    headers: [],
    params: [],
    body: {
      type: 'none',
      raw: '',
      formData: [],
      urlencoded: [],
      json: ''
    }
  },
  response: null,
  loading: false,
  history: []
}

const mutations = {
  SET_CURRENT_REQUEST(state, request) {
    state.currentRequest = { ...state.currentRequest, ...request }
  },
  
  UPDATE_REQUEST_FIELD(state, { field, value }) {
    if (field.includes('.')) {
      const keys = field.split('.')
      let obj = state.currentRequest
      for (let i = 0; i < keys.length - 1; i++) {
        obj = obj[keys[i]]
      }
      obj[keys[keys.length - 1]] = value
    } else {
      state.currentRequest[field] = value
    }
  },
  
  ADD_HEADER(state, header = { key: '', value: '', enabled: true }) {
    state.currentRequest.headers.push(header)
  },
  
  UPDATE_HEADER(state, { index, header }) {
    state.currentRequest.headers[index] = header
  },
  
  REMOVE_HEADER(state, index) {
    state.currentRequest.headers.splice(index, 1)
  },
  
  ADD_PARAM(state, param = { key: '', value: '', enabled: true }) {
    state.currentRequest.params.push(param)
  },
  
  UPDATE_PARAM(state, { index, param }) {
    state.currentRequest.params[index] = param
  },
  
  REMOVE_PARAM(state, index) {
    state.currentRequest.params.splice(index, 1)
  },
  
  SET_RESPONSE(state, response) {
    state.response = response
  },
  
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  ADD_TO_HISTORY(state, item) {
    state.history.unshift({
      ...item,
      id: `req_${Date.now()}`,
      timestamp: new Date().toISOString()
    })
    if (state.history.length > 100) {
      state.history = state.history.slice(0, 100)
    }
  },
  
  CLEAR_HISTORY(state) {
    state.history = []
  }
}

const actions = {
  async sendRequest({ state, commit, dispatch }) {
    commit('SET_LOADING', true)
    commit('SET_RESPONSE', null)
    
    const { method, url, headers, params, body } = state.currentRequest
    
    if (!url) {
      commit('SET_LOADING', false)
      return { error: true, message: 'URL is required' }
    }
    
    const config = {
      method,
      url,
      headers: {},
      params: {}
    }
    
    headers.filter(h => h.enabled && h.key).forEach(h => {
      config.headers[h.key] = h.value
    })
    
    params.filter(p => p.enabled && p.key).forEach(p => {
      config.params[p.key] = p.value
    })
    
    if (method !== 'GET' && method !== 'HEAD') {
      switch (body.type) {
        case 'raw':
          config.data = body.raw
          break
        case 'json':
          try {
            config.data = JSON.parse(body.json)
            config.headers['Content-Type'] = 'application/json'
          } catch (e) {
            commit('SET_LOADING', false)
            return { error: true, message: 'Invalid JSON' }
          }
          break
        case 'formData':
          const formData = new FormData()
          body.formData.filter(f => f.enabled && f.key).forEach(f => {
            formData.append(f.key, f.value)
          })
          config.data = formData
          break
        case 'urlencoded':
          const urlencoded = new URLSearchParams()
          body.urlencoded.filter(u => u.enabled && u.key).forEach(u => {
            urlencoded.append(u.key, u.value)
          })
          config.data = urlencoded.toString()
          config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
          break
      }
    }
    
    try {
      console.log('发送请求:', config)
      const response = await httpClient.request(config)
      console.log('收到响应:', response)
      
      commit('SET_RESPONSE', response)
      commit('ADD_TO_HISTORY', {
        method,
        url,
        status: response.status,
        statusText: response.statusText,
        success: !response.error
      })
      
      dispatch('history/addItem', {
        type: 'http',
        method,
        url,
        request: state.currentRequest,
        response
      }, { root: true })
      
      return response
    } catch (error) {
      const errorResponse = {
        error: true,
        message: error.message
      }
      commit('SET_RESPONSE', errorResponse)
      commit('ADD_TO_HISTORY', {
        method,
        url,
        status: 0,
        statusText: 'Error',
        success: false
      })
      return errorResponse
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  updateRequestField({ commit }, payload) {
    commit('UPDATE_REQUEST_FIELD', payload)
  },
  
  addHeader({ commit }) {
    commit('ADD_HEADER')
  },
  
  updateHeader({ commit }, payload) {
    commit('UPDATE_HEADER', payload)
  },
  
  removeHeader({ commit }, index) {
    commit('REMOVE_HEADER', index)
  },
  
  addParam({ commit }) {
    commit('ADD_PARAM')
  },
  
  updateParam({ commit }, payload) {
    commit('UPDATE_PARAM', payload)
  },
  
  removeParam({ commit }, index) {
    commit('REMOVE_PARAM', index)
  },
  
  loadRequestFromHistory({ commit }, request) {
    commit('SET_CURRENT_REQUEST', request)
  },
  
  clearHistory({ commit }) {
    commit('CLEAR_HISTORY')
  },
  
  applyConfig({ commit }, config) {
    if (config.currentRequest) {
      commit('SET_CURRENT_REQUEST', config.currentRequest)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}